package base.thread_JUC2.chapter05.demo01;

import java.util.List;
import java.util.concurrent.RecursiveAction;

/**
 * 任务类，无需返回任务结果，继承 RecursiveAction 即可。
 *
 * 是ForkJoinTask的子类，将被放到 ForkJoinPool中执行。
 */
public class Task extends RecursiveAction {
    // 产品列表
    private List<Product> products;
    // 起始位置
    private int first, last;
    // 增量幅度
    private double increment;

    public Task(List<Product> products, int first, int last, double increment){
        this.products = products;
        this.first = first;
        this.last = last;
        this.increment = increment;
    }


    /**
     * 任务的执行逻辑
     */
    @Override
    protected void compute() {
        if (last - first <10) {
            updatePrices();
        }else{
            // 除2
            int middle = (first + last) >>> 1;
            System.out.printf("Task: 挂起的任务数: %s\n",getQueuedTaskCount());

            Task task1 = new Task(products, first, middle + 1, increment);
            Task task2 = new Task(products, middle + 1, last, increment);
            invokeAll(task1, task2);
        }
    }

    private void updatePrices(){
        for (int i = first; i < last; i++) {
            Product product = products.get(i);
            product.setPrice(product.getPrice()*(1+increment));
        }
    }
}
